<template>
  <div class="play_setting_content padding10">
    <el-divider class="header-title">插播音频（秒）</el-divider>
    <div class="insert_audio_content win-flex-row">
      <el-radio-group v-model="insertAudioSetting.type">
        <el-radio label="anchor">
          <div class="item_content">
            <div class="label">主播</div>
          </div>
        </el-radio>
        <el-radio label="assistant">
          <div class="item_content">
            <div class="label">小助理</div>
          </div>
        </el-radio>
      </el-radio-group>
      <div class="other_content win-flex-cloumn flex-1">
        <div class="win-flex-row flex-y-center mb2">
          <div class="mr5 bgYellow">待生成区:</div>
          <div class="border marquee flex-1">
            <div class="ellipsis">{{ insertAudioWaitGen }}</div>
          </div>
        </div>
        <div class="win-flex-row flex-y-center">
          <div class="mr5 bgBlue">待播放区:</div>
          <div class="border marquee flex-1">
            <div class="ellipsis">{{ insertAudioWaitPlay }}</div>
          </div>
        </div>
      </div>
    </div>
    <el-divider class="header-title">关键字回复（秒）</el-divider>
    <div class="keyword_content win-flex-row">
      <el-radio-group v-model="keywordSetting.type">
        <el-radio label="anchor">
          <div class="item_content">
            <div class="label">主播</div>
          </div>
        </el-radio>
        <el-radio label="assistant">
          <div class="item_content">
            <div class="label">小助理</div>
          </div>
        </el-radio>
      </el-radio-group>
      <div class="other_content win-flex-cloumn">
        <div class="content win-flex-row flex-y-center flex-1">
          <el-switch v-model="keywordSetting.repeatProblem" active-text="复读问题" />
          <div class="mr3 ml3">每</div>
          <el-input-number size="mini" v-model="keywordSetting.startTime" controls-position="right" :min="1"
            :max="100000"></el-input-number>
          <div class="mr3 ml3">到</div>
          <el-input-number size="mini" v-model="keywordSetting.endTime" controls-position="right" :min="1"
            :max="100000"></el-input-number>
          <div class="mr3 ml3">倒计时:</div>
          <div><el-button size="mini" type="warning">{{ keywordCountDownTime }}</el-button></div>
        </div>
        <div class="audio_content win-flex-row flex-y-center flex-1">
          <div class="mr5 bgYellow">待生成区:</div>
          <div class="border marquee flex-1">
            <div class="ellipsis">{{ keywordWaitGen }}</div>
          </div>
          <div class="ml5 mr5 bgBlue">待播放区:</div>
          <div class="border marquee flex-1">
            <div class="ellipsis">{{ keywordWaitPlay }}</div>
          </div>
        </div>
      </div>
    </div>
    <el-divider class="header-title">用户进入（秒）</el-divider>
    <div class="userEnter_content win-flex-row">
      <el-radio-group v-model="userEnterSetting.type">
        <el-radio label="anchor">
          <div class="item_content">
            <div class="label">主播</div>
          </div>
        </el-radio>
        <el-radio label="assistant">
          <div class="item_content">
            <div class="label">小助理</div>
          </div>
        </el-radio>
      </el-radio-group>
      <div class="other_content win-flex-cloumn">
        <div class="content win-flex-row flex-y-center flex-1">
          <div class="mr3">每</div>
          <el-input-number size="mini" v-model="userEnterSetting.startTime" controls-position="right" :min="1"
            :max="100000"></el-input-number>
          <div class="mr3 ml3">到</div>
          <el-input-number size="mini" v-model="userEnterSetting.endTime" controls-position="right" :min="1"
            :max="100000"></el-input-number>
          <div class="mr3 ml3">倒计时:</div>
          <div><el-button size="mini" type="warning">{{ userEnterCountDownTime }}</el-button></div>
        </div>
        <div class="audio_content win-flex-row flex-y-center  flex-1">
          <div class="mr5 bgYellow">待生成区:</div>
          <div class="border marquee flex-1">
            <div class="ellipsis">{{ userEnterWaitGen }}</div>
          </div>
          <div class="ml5 mr5 bgBlue">待播放区:</div>
          <div class="border marquee flex-1">
            <div class="ellipsis">{{ userEnterWaitPlay }}</div>
          </div>
        </div>
      </div>
    </div>
    <el-divider class="header-title">随机音频（秒）</el-divider>
    <div class="random_audio_content w100Rate win-flex-row">
      <div class="randomAudio">
        <el-switch v-model="randomAudioSetting.open"></el-switch>
        <div>随机音频</div>
      </div>
      <div class="other_content win-flex-cloumn">
        <div class="content win-flex-row flex-y-center flex-1">
          <div class="mr3">每</div>
          <el-input-number size="mini" v-model="randomAudioSetting.startTime" controls-position="right" :min="1"
            :max="100000"></el-input-number>
          <div class="mr3 ml3">到</div>
          <el-input-number size="mini" v-model="randomAudioSetting.endTime" controls-position="right" :min="1"
            :max="100000"></el-input-number>
          <div class="mr3 ml3">倒计时:</div>
          <div><el-button size="mini" type="warning">{{ randomAudioCountDownTime }}</el-button></div>
        </div>
        <div class="audio_content win-flex-row flex-y-center  flex-1">
          <div class="mr5 bgYellow">待生成区:</div>
          <div class="border marquee flex-1">
            <div class="ellipsis">{{ randomAudioWaitGen }}</div>
          </div>
          <div class="ml5 mr5 bgBlue">待播放区:</div>
          <div class="border marquee flex-1">
            <div class="ellipsis">{{ randomAudioWaitPlay }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="oper win-flex-row">
      <el-button class="w100Rate" v-if="liveStatus == 0" style="height: 40px;" type="primary" @click="startLive">
        开启实时直播</el-button>
      <el-button class="w100Rate" v-if="liveStatus == 1" style="height: 40px;" type="danger" @click="stopLive">
        关闭实时直播
      </el-button>
      <el-button class="w100Rate" v-if="liveStatus == 1" style="height: 40px;" type="danger" @click="pauseLive">{{
        pauseStatus == 0 ? '暂停直播' : '继续直播'
      }}</el-button>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { EventBus } from '@/event-bus.js';
import { start, stop } from '@/api/live/live';
import { sse } from './mixins/sse';
import { getRandomInRange } from '@/utils/util';
import { getLiveStatus, setLiveStatus } from '@/api/bvmodel/bvmodel';
export default {
  name: 'PlaySetting',
  mixins: [sse],
  components: {
  },
  data() {
    return {
      startLiveInstance: null,
      //直播状态 0 关闭  1开启成功
      liveStatus: 0,
      pauseStatus: 0,
      keywordCountDownTime: 0,
      userEnterCountDownTime: 0,
      randomAudioCountDownTime: 0,
      intervalIds: [],
      pollInterval: null,     // 轮询直播间状态计时器
    };
  },
  created() {
    this.checkLiveStatus();
  },
  // 组件销毁时清除所有定时器
  beforeDestroy() {
    this.clearIntervalIds();
  },
  computed: {
    userEnterSetting() {
      return this.pageConfig.userEnterSetting;
    },
    insertAudioSetting() {
      return this.pageConfig.insertAudioSetting;
    },
    keywordSetting() {
      return this.pageConfig.keywordSetting;
    },
    randomAudioSetting() {
      return this.pageConfig.randomAudioSetting;
    },
    fileDirectory() {
      return this.pageConfig.fileDirectory;
    },
    pageConfig() {
      return this.$store.state.page.config;
    },
  },
  watch: {
  },
  methods: {
    checkLiveStatus() {
      getLiveStatus().then((res) => {
        if (res.msg != 'stop') {
          this.setConnect();
          this.liveAfterHandler();
          if (res.msg == 'pause') {
            this.pauseStatus = 1;
            //暂停直播了
            this.clearIntervalIds();
          }
        }
      });
    },
    clearIntervalIds() {
      Object.values(this.intervalIds).forEach(id => clearInterval(id))
    },
    startCountdown(type) {
      const intervalId = setInterval(() => {
        const timeProp = `${type}CountDownTime`;
        if (this[timeProp] > 0) {
          this[timeProp]--;
        } else {
          // 倒计时结束，重新生成时间
          this[timeProp] = getRandomInRange(
            this[`${type}Setting`].startTime,
            this[`${type}Setting`].endTime
          );
          // 触发回调（示例）
          this.handleCountdownEnd(type);
        }
      }, 1000);
      this.intervalIds.push(intervalId);
    },
    // 倒计时结束处理（按需扩展）
    handleCountdownEnd(type) {
      //这个地方需要去发送消息给websocket
      EventBus.$emit(`${type}MatchSendWebSocket`, {});
    },
    genRangeNumberAndCountDown(needGen = true) {
      //开启直播之后 需要进行随机一个数然后倒计时
      if (this.randomAudioSetting.open) {
        if (needGen) {
          this.randomAudioCountDownTime = getRandomInRange(this.randomAudioSetting.startTime, this.randomAudioSetting.endTime);
        }
        this.startCountdown('randomAudio');
      }
      if (this.userEnterSetting.open) {
        if (needGen) {
          this.userEnterCountDownTime = getRandomInRange(this.userEnterSetting.startTime, this.userEnterSetting.endTime);
        }
        this.startCountdown('userEnter');
      }
      if (this.keywordSetting.open) {
        if (needGen) {
          this.keywordCountDownTime = getRandomInRange(this.keywordSetting.startTime, this.keywordSetting.endTime);
        }
        this.startCountdown('keyword');
      }
    },
    ...mapActions({
      setLiveCurrentlyOnlineCount: 'setLiveCurrentlyOnlineCount',
      setLiveTotalPopularityCount: 'setLiveTotalPopularityCount',
    }),
    pauseLive() {
      this.pauseStatus = this.pauseStatus == 0 ? 1 : 0;
      const status = this.pauseStatus == 1 ? 'pause' : 'playing';
      setLiveStatus(status).then(res => {
        if (this.pauseStatus == 1) {
          //暂停直播了
          this.clearIntervalIds();
        } else {
          //重新直播了
          this.genRangeNumberAndCountDown(false);
        }
      });
    },
    /**
     * 开启直播
     */
    async startLive() {
      if (!this.fileDirectory.categoryId) {
        this.$message.error("请选择直播话术分类");
        return;
      }
      this.startLiveInstance = this.$modal.loading("正在开启直播...");
      start({
        categoryId: this.fileDirectory.categoryId
      }).then((res) => {
        if (res.code != 200) {
          this.$modal.closeLoading();
          this.$message.error(res.msg);
          return;
        }
        this.setConnect();
      });
    },
    /**
     * 关闭直播
     */
    async stopLive() {
      this.liveStatus = 0;
      this.pauseStatus = 0;
      this.$modal.loading("正在关闭直播...");
      EventBus.$emit('changeLiveStatus', this.liveStatus);
      stop().then(() => {
        this.setLiveCurrentlyOnlineCount(0);
        this.setLiveTotalPopularityCount(0);
        this.connectAbortController?.abort();
        this.$message.success("关闭直播成功");
        this.$modal.closeLoading();
        this.clearIntervalIds();
        this.keywordCountDownTime = 0;
        this.userEnterCountDownTime = 0;
        this.randomAudioCountDownTime = 0;
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.play_setting_content {
  height: 100%;
  width: 500px;
  border-left: 1px solid var(--color-border-first);

  .header-title {
    margin: 12px 0 !important;
  }

  .border {
    border: 1px solid var(--color-border-second);
  }

  .bgYellow {
    background: #f2f265;
  }

  .bgBlue {
    background: #0bff00;
  }

  .marquee {
    height: 28px;
    line-height: 28px;
    padding-left: 15px;
    border-radius: 4px;
    overflow: hidden;
    width: 155px;
  }

  .randomAudio {
    height: 61px;
    font-size: 16px;
    width: 74px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .other_content {
    font-size: 14px;

    .audio_content {
      height: 33px;
    }
  }

  .keyword_content {
    ::v-deep .el-input-number {
      width: 84px !important;

      &.is-controls-right .el-input__inner {
        padding-left: 10px !important;
        padding-right: 30px !important;
      }
    }
  }

  .content {
    ::v-deep .el-input-number {
      width: 136px;
    }

    ::v-deep .el-button {
      padding: 7px 14px;
    }
  }

  .el-radio {
    display: block;
    margin-right: 0px;
    margin-bottom: 0px;
    width: 100%;

    &:first-child {
      margin-bottom: 7px;
    }

    ::v-deep .el-radio__label {
      display: inline-block;
      width: calc(100% - 22px);
    }


    .item_content {
      display: flex;
      height: 26px;
      line-height: 26px;
      justify-content: center;
      align-items: center;
      color: #000;

      .label {
        width: 50px;
      }

    }
  }
}
</style>
